<?php

namespace App\Http\Controllers\Api;

use App\Models\Product;
use App\Models\CartItem;
use App\Models\ProductSku;
use Illuminate\Http\Request;
use App\Services\CartService;

class CartController extends ApiController
{
    protected $cartService;

    // 利用 Laravel 的自动解析功能注入 CartService 类
    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    public function index(Request $request)
    {
        $cartItems = $this->cartService->get();

        $data['cartItems'] = $cartItems;
        return $this->success($data);
    }

    public function add(Request $request)
    {
        $data = $this->CheckProduct($request->sku_id, $request->amount);
        if($data['res'])
        {
            $this->cartService->add($request->sku_id,$request->amount);
            return $this->success('');
        }
        return $this->success($data['msg'],'error');
    }
    public function increase(Request $request)
    {
        $data = $this->CheckProduct($request->sku_id, $request->amount);
        if($data['res'])
        {
            $this->cartService->increase($request->cartitem_id, $request->amount);
            return $this->success('');
        }
        return $this->success($data['msg'],'error');
    }
    public function decrease(Request $request)
    {
        if (!$p = ProductSku::find($request->sku_id)) {
            return $this->success('该商品不存在','error');
        }
        if (!$p->product->on_sale) {
            return $this->success('该商品未上架','error');
        }
        $this->cartService->decrease($request->cartitem_id, $request->amount);
        return $this->success('');
    }
    public function remove(Request $request)
    {
        $this->cartService->remove($request->ids);

        return $this->success('');
    }
    public function CheckProduct($product_sku_id,$amount)
    {
        $data = ['res'=>true,'msg'=>''];
        if (!$p = ProductSku::find($product_sku_id)) {
            $data = ['res'=>false,'msg'=>'该商品不存在'];
            return $data;
        }
        if (!$p->product->on_sale) {
            $data = ['res'=>false,'msg'=>'该商品未上架'];
            return $data;
        }
        if ($p->stock === 0) {
            $data = ['res'=>false,'msg'=>'该商品已售完'];
            return $data;
        }
        if ($amount > 0 && $p->stock < $amount) {
            $data = ['res'=>false,'msg'=>'该商品库存不足'];
            return $data;
        }
      	return $data;
    }
}